// 导入express
const express = require("express");
const bodyParser = require("body-parser");
const db = require("./db");
const cors = require("cors");
const jwt = require("jsonwebtoken");

const router = express.Router();

const fetch = require("node-fetch");
const llamaApi = async (msg) => {
  try {
    const response = await fetch(
      "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "sk-f7781b216b88400fa20270cfc92260a4",
        },
        body: JSON.stringify({
          model: "qwen-turbo",
          // model: "llama3-8b-instruct",
          input: {
            messages: [
              { role: "system", content: "You are a helpful assistant." },
              { role: "user", content: msg },
            ],
          },
        }),
      }
    );
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error, "模型错误了");
    return false;
  }
};

// 调用函数
// llamaApi("苹果该怎么种植");

// 创建应用对象
const app = express();
//跨域
app.use(cors());
// 解析JSON格式的请求体
app.use(bodyParser.json());
// 或解析表单数据（application/x-www-form-urlencoded）
app.use(bodyParser.urlencoded({ extended: true }));

// 创建token认证
const secret = "ultraman"; //解密密钥
const JWT = {
  createToken: (data, time) => {
    return jwt.sign(data, secret, { expiresIn: time });
  },
  verifyToken: (token) => {
    // 如果token过期或验证失败，将返回false
    try {
      return jwt.verify(token, secret);
    } catch (error) {
      return false;
    }
  },
};
let token = ""; // 测试用的token

/**
 * 拦截器
 */
// app.use(function (req, res, next) {
//   let token = req.body.token;
//   if (JWT.verifyToken(token)) {
//     //用户登录过
//     console.log("用户已登录");
//     console.log(req.body.token);
//     next();
//   } else {
//     //解析用户请求路径
//     var arr = req.url.split("/");
//     //去除get请求携带的参数
//     for (var i = 0; i < arr.length; i++) {
//       arr[i] = arr[i].split("?")[0];
//     }
//     if (arr.length > 1) {
//       if (arr[1] === "login" || arr[1] === "sigin") {
//         next();
//       } else {
//         res.send({ code: 301 });
//         res.end();
//       }
//     }
//   }
// });

// 创建路由规则
app.get("/home", (request, response) => {
  let a = {
    b: "12asdasd3",
    c: "2123",
  };
  response.end(JSON.stringify(a));
});

app.get("/", (req, res) => {
  let sqlQuery = "SELECT * FROM users";
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }

    res.send(resData);
  });
});

// 用户登录
app.post("/login", (req, res) => {
  // res.send(req.body)
  let sqlQuery = `SELECT * FROM users WHERE userName = "${req.body.userName}" AND password = "${req.body.password}";`;
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }
    // 生成token
    token = JWT.createToken(
      { userName: req.body.userName, password: req.body.password },
      "1day"
    );
    res.send({ code: 200, token: token, data: resData });
    // res.send(resData);
  });
});

// 用户注册
app.post("/sigin", (req, res) => {
  // res.send(req.body)
  let sqlQuery = `SELECT * FROM users WHERE userName = "${req.body.userName}" `;
  let sqlInsert = `INSERT INTO users (userName , password) VALUES (${req.body.userName} , ${req.body.password});`;
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }
    // 代表可以注册
    if (resData.length == 0) {
      db.query(sqlInsert, (err, resData, fie) => {
        if (err) {
          throw err;
        }
        // 生成token
        token = JWT.createToken(
          { userName: req.body.userName, password: req.body.password },
          "1day"
        );
        res.send({ code: 200, token: token });
      });
    } else {
      res.send({ code: -1 });
    }
  });
});

// 用户信息
app.post("/user", (req, res) => {
  // res.send(req.body)
  let sqlQuery = `SELECT * FROM users WHERE userName = "${req.body.userName}"`;
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }
    // // 验证token
    // console.log(req.body.token);
    // let ress = JWT.verifyToken(req.body.token);
    // res.send(ress);
    res.send(resData);
  });
});

// 返回所有文章
app.post("/allArtical", (req, res) => {
  // res.send(req.body)
  let sqlQuery = `SELECT 
  a.*,
  CASE 
      WHEN EXISTS(SELECT 1 FROM user_article_collections uac WHERE uac.Uid = (SELECT Uid FROM users WHERE userName = "${req.body.userName}") AND uac.Aid = a.Aid) THEN 1 
      ELSE 0 
  END AS isCollect
FROM 
  artical a;`;
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }
    res.send(resData);
  });
});

// 收藏
app.post("/collect", (req, res) => {
  // res.send(req.body)
  let Uid = req.body.Uid;
  let Aid = req.body.Aid;
  let sqlQuery = `INSERT INTO user_article_collections (Uid, Aid) VALUE (${Uid},${Aid});`;
  let sqlFind = `SELECT * FROM user_article_collections WHERE UID = ${Uid} AND Aid = ${Aid};`;
  db.query(sqlFind, (err, resData, fie) => {
    if (resData.length != 0) {
      res.send(false);
    } else {
      db.query(sqlQuery, (err, resData, fie) => {
        // db.query(sql, (err, resData, fie) => {});
        if (err) {
          throw err;
        }
        res.send(true);
      });
    }
  });
});
// 取消搜藏
app.post("/noCollect", (req, res) => {
  let Uid = req.body.Uid;
  let Aid = req.body.Aid;
  let sqlQuery = `DELETE FROM user_article_collections WHERE UID = ${Uid} AND Aid = ${Aid};`;
  let sqlFind = `SELECT * FROM user_article_collections WHERE UID = ${Uid} AND Aid = ${Aid};`;
  db.query(sqlFind, (err, resData, fie) => {
    if (!resData) {
      res.send(false);
    } else {
      db.query(sqlQuery, (err, resData, fie) => {
        // db.query(sql, (err, resData, fie) => {});
        if (err) {
          throw err;
        }
        res.send(true);
      });
    }
  });
});

// 返回用户收藏的文章
app.post("/allCollect", (req, res) => {
  let Uid = req.body.Uid;
  // res.send(req.body)
  let sqlQuery = `SELECT * FROM artical a 
  JOIN user_article_collections uac ON a.Aid = uac.Aid
  WHERE uac.Uid = ${Uid}
  `;
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }
    res.send(resData);
  });
});

// 写文章
app.post("/writeArtical", (req, res) => {
  let Uid = req.body.Uid;
  let abstract = req.body.abstract;
  let author = req.body.author;
  let comment = req.body.comment;
  let content = req.body.content;
  let date = req.body.date;
  let isCollect = req.body.isCollect;
  let numCollect = req.body.numCollect;
  let title = req.body.title;
  let sqlQuery = `INSERT INTO artical ( title, abstract, date, author, comment, content, isCollect, numCollect)
  VALUES
  ( '${title}', '${abstract}',  '${date}',  '${author}',  ${comment},  '${content}',  ${isCollect},  ${numCollect});
  `;
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }
    res.send(resData);
  });
});

// 我的文章
app.post("/myArtical", (req, res) => {
  let userName = req.body.userName;
  // res.send(req.body)
  let sqlQuery = `SELECT * FROM artical
  WHERE author = '${userName}';
  `;
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }
    res.send(resData);
  });
});

// 观看了某一个文章【浏览量】
app.post("/lookArtical", (req, res) => {
  let Aid = req.body.Aid;
  // res.send(req.body)
  let sqlQuery = `UPDATE artical
  SET comment = comment + 1
  WHERE Aid = ${Aid};
  `;
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }
    res.send(resData);
  });
});
// 用户观看了某一个文章【更新观看历史】
app.post("/lookAdd", (req, res) => {
  let Uid = req.body.Uid;
  let Aid = req.body.Aid;
  // res.send(req.body)
  let sqlQuery = `INSERT INTO user_article_views (Uid, Aid)
  VALUES (${Uid}, ${Aid});
  `;
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }
    res.send(resData);
  });
});

// 观看记录
app.post("/lookHistory", (req, res) => {
  let userName = req.body.userName;
  // res.send(req.body)
  let sqlQuery = `SELECT a.title, a.abstract, uav.viewTime
  FROM user_article_views uav
  JOIN artical a ON uav.Aid = a.Aid
  JOIN users u ON uav.Uid = u.Uid
  WHERE u.UserName = '${userName}'
  ORDER BY uav.viewTime DESC;
  `;
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }
    res.send(resData);
  });
});

// 获取聊天记录
app.post("/getChatList", (req, res) => {
  let Uid = req.body.Uid;
  // res.send(req.body)
  let sqlQuery = `
  SELECT * FROM conversation_records
WHERE Uid = ${Uid}
ORDER BY RecordId, RecordId ASC;
  `;
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }
    res.send(resData);
  });
});
// 对话聊天
app.post("/postChat", (req, res) => {
  let Uid = req.body.Uid;
  let msg = req.body.msg;
  let time = req.body.time;
  let sqlQuery = `
  INSERT INTO conversation_records (Uid, Speaker, DialogueContent, DialogueDate)
  VALUES 
      (${Uid}, 'USER', '${msg}', '${time}');
  `;
  db.query(sqlQuery, (err, resData, fie) => {
    if (err) {
      throw err;
    }
  });

  // console.log(msg, "22222");
  llamaApi(msg).then((resData) => {
    let text = resData.output.text.replace(/[\r\n]+/g, " ");
    console.log(text);
    let sqlQuery2 = `
    INSERT INTO conversation_records (Uid, Speaker, DialogueContent, DialogueDate)
    VALUES
        (${Uid}, 'AI', '${text}', '${time}');
    `;
    db.query(sqlQuery2, (err, resData, fie) => {
      if (err) {
        throw err;
      }
      res.send(text);
    });
  });
});

// 启动服务，并监听端口
app.listen(9000, () => {
  console.log("服务器启动了 localhost:9000/");
});
